package org.platform.tool.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class TimeUtils {
    private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * @return
     */
    public static String getSystemCurrentTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_FORMAT);
        String date = dateFormat.format(new Date());
        return date;
    }

    public static String getTimeByFormat() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_FORMAT);
        String date = dateFormat.format(new Date());
        return date;
    }

    /**
     * @return
     */
    public static long getCurrentTimeMillis() {
        long time = System.currentTimeMillis();
        return time;
    }

    /**
     * 自定义返回的时间格式
     *
     * @param format
     * @return
     */
    public static String getTimeByFormat(String format) {
        if (StringUtils.isNotEmpty(format)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            return dateFormat.format(new Date());
        } else {
            return getSystemCurrentTime();
        }
    }

    /**
     * 根据格式,将字符串时间 转 时间搓
     *
     * @param format
     * @return
     */
    public static long strTimeToTimestampsByFormat(String time, String format) {
        long t = 0;
        if (StringUtils.isNotEmpty(time)) {
            if (StringUtils.isEmpty(format)) {
                format = DEFAULT_FORMAT;
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            try {
                t = dateFormat.parse(time).getTime();
            } catch (ParseException e) {
                log.error("时间转换异常: ", e);
            }
        }
        return t;
    }

    /**
     * 时间戳转时间
     *
     * @param timestamps
     * @return
     */
    public static String timestampsToStr(long timestamps) {
        Date date = new Date(timestamps);
        return new SimpleDateFormat(DEFAULT_FORMAT).format(date);
    }

    public static String timestampsToStr(long timestamps, String format) {
        Date date = new Date(timestamps);
        return new SimpleDateFormat(format).format(date);
    }

}
